package com.scs.application.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.CacheUtils;
import com.scs.application.modules.sys.entity.Flow;
import com.scs.application.modules.sys.entity.FlowNode;
import com.scs.application.modules.sys.mapper.FlowNodeMapper;
import com.scs.application.modules.sys.service.FlowNodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class FlowNodeServiceImpl extends BaseServiceImpl<FlowNodeMapper, FlowNode> implements FlowNodeService {

    @Autowired
    private FlowServiceImpl flowService;

    @Override
    public List<FlowNode> getByFlowId(String flowId) {
        return this.list(Wrappers.<FlowNode>query().eq("flow_id", flowId));
    }
    @Override
    public List<FlowNode> getByFlowCode(String flowCode) {
        Flow flow = flowService.getOne(Wrappers.<Flow>query().eq("code", flowCode));
        if (flow == null) {
            return null;
        }
        return this.list(Wrappers.<FlowNode>query().eq("flow_id", flow.getId()));
    }

    @Override
    public Boolean isSupport(Boolean flagProject) {
        return flagProject;
    }


    /**
     * @Description：根据FlowId和FlowNodeValue获取节点
     */
    @Override
    public FlowNode getByFlowIdAndValue(String flowId, String nodeValue) {
        return this.getOne(Wrappers.<FlowNode>query().eq("flow_id", flowId).eq("value", nodeValue));
    }

    @Override
    public boolean saveOrUpdate(FlowNode flowNode) {
        Flow flow = flowService.getById(flowNode.getFlowId());
        if (flow != null) {
            CacheUtils.remove(CacheUtils.FLOW_NODE_CACHE, flow.getCode());
        }
        return super.saveOrUpdate(flowNode);
    }

    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        if (idList.isEmpty()) {
            return false;
        }
        List<FlowNode> flowNodes = this.list(Wrappers.<FlowNode>query().in("id", idList));
        if (!flowNodes.isEmpty()) {
            Flow flow = flowService.getById(flowNodes.get(0).getFlowId());
            if (flow != null) {
                CacheUtils.remove(CacheUtils.FLOW_NODE_CACHE, flow.getCode());
            }
        }
        return super.removeCascadeByIds(idList);
    }
}
